// Created by liusc on 2020/8/5-9:24.
import { getDict } from "~/utils";
import { getItem, getItem2, getObj, putObj2, putObj3, startBudgetApply } from "@/views/wy-budget/api/budgetapply.js";
import uploadMedia from "@/components/upload-media";
import { getFiles, checkFiles, delFiles } from "@/views/wy-budget/api/fileoperation.js";
import Budget from '@/assets/vue-mixin/budget'
import fileUpload from '@/views/wy-budget/components/fileUpload'

export default {
    name: "apply_add",
    mixins: [Budget],
    components: { uploadMedia, fileUpload },
    data () {
        var doubleValidate = (rule, value, callback) => {
            let reg = /^[0-9]+(.[0-9]{1,2})?$/;
            let lable = rule.message;
            if (!reg.test(value)) {
                return callback(new Error("数值格式错误"));
            } else {
                callback();
            }
        };

        return {
            fileId: '',
            fileId2: '',
            isShow: false,
            fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
            uploadFileList: [],
            fileList: [],
            modelType: "budgetApply",
            isEdit: true,
            busId: "",
            form: {
                applyData: {
                    applyId: "",
                    budgetId: "",
                    budgetCode: "",
                    applyName: "",
                    applyDept: "",
                    applyType: "",
                    budgetSum: "",
                    remarks: "",
                    fileId: "",
                    fileId2: "",
                },
                itemValueList: [],
                operateType: ""
            },

            rules: {
                applyData: {
                    budgetSum: [
                        {
                            required: true,
                            message: "请输入预算总金额",
                            trigger: "blur"
                        },
                        { validator: doubleValidate, trigger: "blur" }
                    ],
                    remarks: [
                        {
                            required: true,
                            message: "请输入费用说明",
                            trigger: "blur"
                        },
                        {
                            min: 0,
                            max: 100,
                            message: "长度在 0 到 100 个字符",
                            trigger: "blur"
                        }
                    ]
                }
            }
        };
    },
    computed: {
        applyDept2: function () {
            let types = getDict("budget_department");
            let pv = this.form.applyData.applyDept;
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv);
                return pts ? pts[0].label : "";
            }
            return "";
        },

        applyType2: function () {
            let types = getDict("budget_type");
            let pv = this.form.applyData.applyType;
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv);
                return pts ? pts[0].label : "";
            }
            return "";
        }
    },

    beforeMount () {
        this.fileId = this.$route.query.fileId
        this.fileId2 = this.$route.query.fileId2

        const loading = this.$loading({
            lock: true,
            text: '数据加载中'
        });
        getObj(this.$route.query.applyId).then(respData => {
            this.$refs["add-form"].resetFields();
            this.form.applyData = respData.data.data;
            this.initItem(this.form.applyData.applyId);
            loading.close()
        }).catch(e => {
            loading.close();
            this.$message({
                type: "error",
                message: "数据获取失败!"
            });
        });
    },

    methods: {
        // 科目
        initItem () {
            getItem2(this.form.applyData.applyId).then(rep => {
                let rspD = rep.data.data;
                rspD && (this.form.itemValueList = rspD.map((item, index) => {
                    return { ...item, isNead: '1', sortNum: index + 1, children: item.children ? item.children.map(it => ({ ...it, isNead: '1' })) : item.children }
                }))
            });
        },

        // 取消
        cancel () {
            this.closeNowRouter();
        },
        // cqg校验必输
        checkWillBe () {
            const reg = /^\d{0,15}(\.\d{0,2})?$/
            let list = this.form.itemValueList.reduce((total, item) => {
                if (item.children) {
                    return total.concat(item.children.filter(it => it.isNead != 0))
                } else {
                    return item.isNead != 0 ? [...total, item] : total
                }
            }, [])
            //只有必填的校验合法值
            //let tips = list.find(item => (item.isNead === '1' && (!item.itemValue || !reg.test(`${item.itemValue}`))) || (item.isNead != '1' && !reg.test(`${item.itemValue}`)) )
            //全必填 
            let tips = list.find(item => item.itemValue == null || item.itemValue == '' || !reg.test(`${item.itemValue}`))
            if (tips) {
                if (tips.itemValue == '' || tips.itemValue == null) {
                    this.$message.warning(`科目"${tips.itemName} " 金额为空，请输入完整金额`);
                    return false
                } else {
                    this.$message.warning(`科目"${tips.itemName} " 金额不正确，请输入合理金额`);
                    return false
                }
            }
            return true
        },

        // 保存
        addCommit () {
            this.form.operateType = "1";
            this.checkWillBe() && this.$refs["add-form"].validate(valid => {
                valid && this.$refs.fileUpload.submit()
            });
        },

        sendFormData (val) {
            //this.loadAction("请稍等...");

            if (val && this.isEdit) {
                //this.form.applyData.fileId2 = val;
                this.busId = val;
                this.isEdit = false;
            }

            this.form.applyData.fileId = this.$route.query.fileId
            this.form.applyData.fileId2 = this.$route.query.fileId2

            putObj3(this.form).then(rep => {
                getObj(this.$route.query.applyId).then(respData => {
                    startBudgetApply(respData.data.data).then(respData => {
                    }).catch(e => {
                    });
                }).catch(e => {
                });

                this.success_message("保存成功");
                //this.loadClose();
                this.closeNowRouter();
            }).catch(e => {
                this.errormessage("保存失败");
                //this.loadClose();
            });
        },

        success_message (msg) {
            this.$message({
                type: "success",
                message: msg
            });
        },

        errormessage (msg) {
            this.$message({
                type: "error",
                message: msg
            });
        },

        closeNowRouter () {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            //跳转
            this.$router.push({ name: "apply_list" });
        },

        // 上传成功监听
        handleCompleted (data) {
            this.sendFormData(data)
        },

        onSuccess (rep, file, fileList) {
            //文件上传成功，开始保存表单
            //this.loadClose();
            if (rep.data != null) {
                this.sendFormData(rep.data);
            } else {
                this.err("提交失败");
            }
        },

        onError (err, file, fileList) {
            //this.loadClose();
            this.err("提交失败");
        },

        beforeUpload () {
            //this.loadAction("请稍等...");
        },

        // 下载
        handleClean (file) {
            this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    delFiles(file.fileId, this.modelType).then(resp => {
                        if (resp.data.code === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });

                            //this.fileList = []
                            this.fileList = this.fileList.filter(
                                file => file.fileId != fileId
                            );
                        } else {
                            this.$message({
                                type: "error",
                                message: "删除失败!"
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        }
    }
};
